package handler

import (
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/mojocn/base64Captcha"
	"net/http"
	"note/service/repository"
	"note/service/util"
	"strings"
)

type auth struct {
	Id       string `json:"id"`       //验证码id
	Username string `json:"username"` // 用户名
	Password string `json:"password"` // 密码
	Code     string `json:"code"`     // 验证码
}

// @Summary   获取登录token 信息
// @Tags auth
// @Accept json
// @Produce  json
// @Param   body  body   auth   true "body"
// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
// @Failure 400 {string} json
// @Router /auth  [POST]
func Auth(c echo.Context) error {
	//反序列化
	var reqInfo auth
	if err := c.Bind(&reqInfo); err != nil {
		return c.JSON(http.StatusBadRequest, util.INVALID_PARAMS)
	}

	//检验验证码
	verifyResult := base64Captcha.VerifyCaptcha(reqInfo.Id, reqInfo.Code)
	if !verifyResult {
		body := map[string]interface{}{"code": "error", "data": "验证失败", "msg": "captcha failed"}
		return c.JSON(http.StatusOK, body)
	}
	//TODO 校验用户账号密码

	//生成token
	token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, util.ERROR_AUTH_TOKEN)
	}
	body := map[string]interface{}{"code": 1, "data": token, "msg": "success"}
	return c.JSON(http.StatusOK, body)
}

// @Summary   获取验证码
// @Tags code
// @Accept json
// @Produce  json
// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
// @Failure 400 {string} json
// @Router /captcha  [GET]
func Captcha(c echo.Context) error {

	captchaId, captcaInterfaceInstance := base64Captcha.GenerateCaptcha("", Base64CaptchaConfigDigit)
	base64blob := base64Captcha.CaptchaWriteToBase64Encoding(captcaInterfaceInstance)

	body := map[string]interface{}{"code": 1, "data": base64blob, "captchaId": captchaId, "msg": "success"}
	return c.JSON(http.StatusOK, body)
}

// @Summary   获取地区
// @Tags api
// @Accept json
// @Produce  json
// @Param  id  id   string true "id"
// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
// @Failure 400 {string} json
// @Router /api/area  [GET]
func GetArea(c echo.Context) error {
	id := c.FormValue("id")
	var (
		body []*repository.Districts
		err  error
	)

	if id == "" {
		body, err = districtsRepository.FindFilter("level=?", 2)
	} else {
		body, err = districtsRepository.FindFilter("parent_id=?", id)
	}

	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, body)
}

// @Summary   根据地区获取学校
// @Tags api
// @Accept json
// @Produce  json
// @Param  id  id   string true "id"
// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
// @Failure 400 {string} json
// @Router /api/school  [GET]
func GetSchools(c echo.Context) error {
	id := c.FormValue("id")
	var (
		body []*repository.Schools
		err  error
	)
	if id != "" {
		body, err = schoolsRepository.FindFilter("country=?", id)
	}
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, body)

}

type order struct {
	OrderId    string `json:"order_id"`
	City       int    `json:"city"`
	Country    int    `json:"country"`
	SchoolId   int    `json:"school_id"`
	SchoolName string `json:"school_name"`
	OrderState string `json:"order_state"`
	Name       string `json:"name"`
	Begin      string `json:"begin"`
	End        string `json:"end"`
}

// @Summary  	获取订单
// @Tags api
// @Accept json
// @Produce  json
// @Param  body  body  order true "body"
// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
// @Failure 400 {string} json
// @Router /api/order  [GET]
func GetOrder(c echo.Context) error {
	//反序列化
	var reqInfo order
	if err := c.Bind(&reqInfo); err != nil {
		return c.JSON(http.StatusBadRequest, util.INVALID_PARAMS)
	}
	var (
		data []*repository.Orders
		err  error
		doc  *repository.Orders
	)

	//如果有id 则直接查询
	if reqInfo.OrderId != "" {
		doc, err = ordersRepository.FindById(reqInfo.OrderId)
		data = []*repository.Orders{doc}
	} else {
		//拼接sql
		var sb strings.Builder
		sb.WriteString(`
	SELECT
		orders.* 
	FROM
		orders
		INNER JOIN goods_order ON orders.order_id = goods_order.order_id
	`)
		//有时间，以及学生名称，则过滤，以及id
		if reqInfo.Name != "" {
			sb.WriteString(fmt.Sprintf("AND orders.username = '%s'", reqInfo.Name))
		}
		if reqInfo.OrderState != "" {
			sb.WriteString(fmt.Sprintf("	AND orders.pay_status= '%s'", reqInfo.OrderState))
		}
		if reqInfo.Begin != "" {
			sb.WriteString(fmt.Sprintf("	AND orders.created_at >= DATE('%s') ", reqInfo.Begin))
		}
		if reqInfo.End != "" {
			sb.WriteString(fmt.Sprintf("	AND orders.created_at <= DATE('%s') ", reqInfo.End))
		}

		//连接学校表
		sb.WriteString("INNER JOIN schools ON goods_order.school_id = schools.id")
		if reqInfo.City != 0 {
			sb.WriteString(fmt.Sprintf("	AND schools.city=%d ", reqInfo.City))
		}
		if reqInfo.Country != 0 {
			sb.WriteString(fmt.Sprintf("	AND schools.country=%d ", reqInfo.Country))
		}
		if reqInfo.SchoolId != 0 {
			sb.WriteString(fmt.Sprintf("	AND schools.id=%d", reqInfo.SchoolId))
		} else {
			if reqInfo.Name != "" {
				sb.WriteString(fmt.Sprintf("	AND schools.`name` LIKE '%%s%'", reqInfo.SchoolName))
			}
		}
		data, err = ordersRepository.Sql(sb.String())
	}
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, data)
}
